import * as echarts from 'echarts'
import { get } from 'lodash-es'
import { useEffect, useRef } from "react"
import { EChartsRenderTypeEnum } from '@/enums';

export type EChartTheme = 'light' | 'dark'

interface UseEChartsOpts {
  click?: (rect: DOMRect) => void;
}

interface DoActionOpts {
  evt: 'click' | 'change';
  data: any;
}

export function useECharts(ref: React.RefObject<HTMLDivElement>, theme: EChartTheme = 'light', opts?: UseEChartsOpts) {
  const echartInstance = useRef<echarts.ECharts>();

  useEffect(() => {
    initEChart();
  }, [ref]) 

  function doAction({ evt, data }: DoActionOpts) {
    const dispatchEvt = get(opts, evt);
    if (dispatchEvt) {
      dispatchEvt(data)
    }
  }

  function initEChart() {
    echartInstance.current = echarts.init(ref.current, theme, {
      renderer: EChartsRenderTypeEnum.Canvas
    });

    // const svgDom = ref.current?.querySelector('canvas');
    // svgDom?.addEventListener('click', (e) => {
    //   console.log('click ', e)
    //   const rect = (e.target as Element)?.getBoundingClientRect()
    //   // doAction({ evt: 'click', data: rect });
    // })
  }

  function getEChartCmptPos() {
    const titleGroup = echartInstance.current?.triggerWithContext('action', 'showTip', 'xAxis', 0);
    // const titlePosition = titleGroup.position;
    console.log('Title Position:', titleGroup);
  }

  function setOptions(opts: echarts.EChartsCoreOption) {
    if (echartInstance.current) {
      echartInstance.current.setOption(opts);
    }
  }

  return {
    echarts,
    setOptions,
    echartInstance: echartInstance.current
  }
}